import { SimObject } from './SimObject';
import { City } from './City';
import { Zone } from './buildings/zones/Zone';
import { assetManager } from '../AssetManager';
import { Building } from './buildings';

export class Tile extends SimObject {

    get terrain(): string {
        return 'grass';
    }

    private _building: Building = null;

    constructor(x: number, y: number) {
        super(x, y);
        this.name = `Tile-${this.x}-${this.y}`;
    }

    /**
     */
    get building() {
        return this._building;
    }

    /**
     */
    setBuilding(value: Building) {
        // Remove and dispose resources for existing building
        if (this._building) {
            this._building.dispose();
            this.remove(this._building);
        }

        this._building = value;

        // Add to scene graph
        if (value) {
            this.add(this._building);
        }
    }

    refreshView(city: City) {

        this.building?.refreshView(city);

        if (this.building?.hideTerrain) {
            this.setMesh(null);
        } else {
            const mesh = assetManager.getModel(this.terrain, this);
            mesh.name = this.terrain;
            this.setMesh(mesh);
        }
    }

    simulate(city: City) {
        if (this.building) {
            this.building.simulate(city);
        }
    }

    distanceTo(tile: Tile) {
        return Math.abs(this.x - tile.x) + Math.abs(this.y - tile.y);
    }

    toHTML() {
        let html = `
            <div class="info-heading">Tile</div>
            <span class="info-label">Coordinates </span>
            <span class="info-value">X: ${this.x}, Y: ${this.y}</span>
            <br>
            <span class="info-label">Terrain </span>
            <span class="info-value">${this.terrain}</span>
            <br>
            `;

        if (this.building) {
            html += this.building.toHTML();
        }

        return html;
    }
};